package com.itqf.service.impl;

import com.itqf.dao.AddressDao;
import com.itqf.dao.impl.AddressDaoImpl;
import com.itqf.pojo.Address;
import com.itqf.service.AddressService;
import com.itqf.utils.StrUtils;
import com.itqf.vo.R;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * projectName: gpshop
 *
 * @author: 赵伟风
 * time: 2021/7/22 10:25
 * description:
 */
public class AddressServiceImpl implements AddressService {


    /**
     * 地址保存业务
     *
     * @param map
     * @return
     */
    @Override
    public R saveAddress(Map<String, String[]> map) throws InvocationTargetException, IllegalAccessException, SQLException {

        //1.判断参数问题
        Address address = new Address();
        BeanUtils.populate(address,map);

        if (StrUtils.isEmpty(address.getaPhone())||
                StrUtils.isEmpty(address.getaPerson()) ||
                            StrUtils.isEmpty(address.getaInfo())){
             return R.fail("地址或者联系人或者电话不能为null");
        }

        //2.查询是否存在地址,考虑默认地址问题
        AddressDao addressDao = new AddressDaoImpl();
        //根据查询用户的地址的数量!
        long count = addressDao.queryCount(address.getuId());
        //3.添加地址
        if (count == 0) {
            //设置为默认地址
            address.setaState(1);
        }
        //保存地址数据
        int rows = addressDao.insertAddress(address);

        //4.返回响应
        if (rows == 0) {
            return R.fail("地址保存失败!请稍后再试!");
        }
        //地址保存成功
        return R.ok();
    }

    /**
     * 根据用户id地址
     *
     * @param uid 地址对应的用户id
     * @return
     */
    @Override
    public List<Address> findAll(int uid) throws SQLException {

        AddressDao addressDao = new AddressDaoImpl();
        /**
         * 根据用户id查询 地址集合
         */
        List<Address> addresses = addressDao.queryAll(uid);

        return addresses;
    }

    /**
     * 设置默认地址
     *
     * @param getuId
     * @param aId
     * @return
     */
    @Override
    public R setDefualt(int uId, String aId) throws SQLException {

        AddressDao addressDao = new AddressDaoImpl();
        //1.将用户的所有地址取消默认

        int rows =  addressDao.updateState(uId);

        if (rows == 0){

            return R.fail("地址被清空!");
        }

        //2.设置指定aid为默认
        addressDao.setDefualt(aId);
        //3.响应

        return R.ok("默认地址设置成功");
    }
}
